<?php

namespace app\teacher\controller\say;

use app\common\controller\Frontend;
use app\common\enums\LearnMeansEnum;
use app\common\enums\say\StrangeTypeEnum;
use app\common\model\banxi\Grade;
use app\common\model\banxi\learn\LearnSayQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSayQuestionRecord;
use app\common\model\banxi\learn\LearnSayReviewRecord;
use app\common\model\banxi\learn\LearnSayReviewSentenceRecord;
use app\common\model\banxi\learn\LearnSkRecord;
use app\common\model\banxi\say\SayTeachSentence;
use app\common\model\banxi\student\StudentSaySentence;
use app\common\service\learn\LearnSkRecordService;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

class Question extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    //列表
    public function listQuestionData()
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query", 'studentId']);
        $user = $this->auth->getUserInfo();
        if (!empty($param['studentId'])) {
            $param['query']['EQ_studentId'] = $param['studentId'];
        } else {
            $param['query']['EQ_trainerId'] = $user['id'];
        }
        $param['query']['EQ_isSubmit'] = 1;
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        //改成学习时间/学习课程/新学句子数/英译汉遗忘句子+遗忘率/考点复现遗忘句子+遗忘率
        $LearnSayVocabularyRecordModel = new LearnSayQuestionRecord();
        $list = $LearnSayVocabularyRecordModel->where($where)
            ->order(['id' => 'desc'])
            ->field('id,sayTeachSentenceName,answerStartTime,translationErrorNum,translationRightRate,answerErrorNum,answerRightRate,learnSentenceCount,useTime')
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit']
            ]);
        $this->ok('ok', result_row($list));
    }

    //开始学习
    public function startQuestion()
    {
        $skRecordId = $this->request->post('skRecordId', null);
        $teachSentenceId = $this->request->post('teachSentenceId');
        $trainerId = $this->auth->id;
        $studentId = null;
        $learnMeans = LearnMeansEnum::E2; // 默认为练习模式（对应 LearnMeans.E2）
        // 如果提供了上课记录ID
        if ($skRecordId) {
            // 查询上课记录
            $learnSkRecord = LearnSkRecord::where('id', $skRecordId)->find();
            // 验证上课记录是否存在
            if (empty($learnSkRecord)) {
                $this->fail('上课记录不存在');
            }

            // 验证教练ID是否匹配
            if ($learnSkRecord['trainerId'] != $trainerId) {
                $this->fail('上课记录不存在');
            }

            // 获取学生ID
            $studentId = $learnSkRecord['studentId'];
            $learnMeans = LearnMeansEnum::E1; // 设置为教学模式（对应 LearnMeans.E1）
        }
        $LearnSkRecordService = new LearnSkRecordService();
        $result = $LearnSkRecordService->startSayQuestion($skRecordId, $studentId, $trainerId, $learnMeans, $teachSentenceId);
        if (!$result) {
            $this->fail($LearnSkRecordService->getError());
        }
        $this->ok('ok', $result);
    }

    //提交答案
    public function answerQuestion()
    {
        $recordId = $this->request->post('recordId', null);
        $answerList = $this->request->filter('')->post('answerList');
        if (!$answerList) {
            $this->fail('提交答案不能为空');
        }
        $trainerId = $this->auth->id;
        $LearnSkRecordService = new LearnSkRecordService();
        $result = $LearnSkRecordService->answerSayQuestion($recordId, $trainerId, null, $answerList);
        if (!$result) {
            $this->fail($LearnSkRecordService->getError());
        }
        $this->ok('ok', $result);
    }

    //获取学习报告(单个)
    public function getSayQuestionReport()
    {
        $questionRecordId = $this->request->get('questionRecordId');
        if (!$questionRecordId) {
            $this->fail('请选择学习记录');
        }


        $LearnSkRecordService = new LearnSkRecordService();
        $result = $LearnSkRecordService->questionReport($questionRecordId);

        $this->ok('ok',$result );
    }


    //设置掌握状态
    public function setCorrectStatus()
    {
        $answerRecordId = $this->request->param('recordId');
        $isCorrect = $this->request->param('isCorrect');
        if (!in_array($isCorrect, [1, 0])) {
            $this->fail('请选择是否掌握');
        }
        $type = $this->request->param('type');//1学习3复习
        switch ($type) {
            case 1:
                //学习
                $recordModel = new LearnSayQuestionRecord();
                $answerModel = new LearnSayQuestionAnswerRecord();
                break;
            case 3:
                //复习
                $recordModel = new LearnSayReviewRecord();
                $answerModel = new LearnSayReviewSentenceRecord();
            default:
                $this->fail('不支持的类型');
        }
        $info = $answerModel->where(['id' => $answerRecordId])->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $recordInfo = $recordModel->where(['id' => $info['recordId']])->field('id,rightNum,errorNum,rightRate')->find();
        if (empty($recordInfo)) {
            $this->fail('学习记录不存在');
        }
        Db::startTrans();
        try {
            if ($info['isCorrect'] != $isCorrect) {
                $info->isCorrect = $isCorrect;
                $info->save();
                $totalNum = $recordInfo['rightNum'] + $recordInfo['errorNum'];
                $rightNum = $isCorrect == 1 ? $recordInfo['rightNum'] + 1 : $recordInfo['rightNum'] - 1;
                $errorNum = $isCorrect == 1 ? $recordInfo['errorNum'] - 1 : $recordInfo['errorNum'] + 1;
                $correctRate = $totalNum > 0 ? intval(($rightNum / $totalNum) * 100) : 0;
                $recordInfo->rightNum = $rightNum;
                $recordInfo->errorNum = $errorNum;
                $recordInfo->rightRate = $correctRate;
                $recordInfo->save();
            }
            if (!empty($info['studentId'])) {
                $sentence = [
                    'studentId' => $info['studentId'],
                    'sayTeachSentenceId' => $info['sayTeachSentenceId'],
                    'strangeType' => StrangeTypeEnum::E1,
                    'sentenceEn' => $info['sentenceEn'],
                    'sentenceZh' => $info['sentenceZh'],
                    'sentencePhonetic' => $info['sentencePhonetic'],
                    'sentenceAudio' => $info['sentenceAudio'],
                    'sentenceImage' => $info['sentenceImage'],
                    'sentenceWordColor' => $info['sentenceWordColor'],
                    'isCorrect' => $isCorrect
                ];
                $StudentSaySentenceModel = new StudentSaySentence();
                $StudentSaySentenceModel->updateStudentSentence($info['studentId'], $sentence, $type);
            }
            Db::commit();
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->fail('fail');
        }

        $this->ok('ok');
    }

}